package com.ncmmall.mall.controller.business.distribution;

import com.ncmmall.application.business.distribution.DistributionGoodsApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.lang.ArithUtils;
import com.feijin.commons.lang.Requires;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.distribution.DistributionGoods;
import com.ncmmall.domain.business.distribution.DistributionGoodsLevel;
import com.ncmmall.domain.business.distribution.Distributor;
import com.ncmmall.domain.business.distribution.DistributorLevel;
import com.ncmmall.domain.business.distribution.QDistributionGoods;
import com.ncmmall.domain.business.distribution.QDistributionGoodsLevel;
import com.ncmmall.domain.business.distribution.QDistributorLevel;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分销商品池管理
 *
 * @author likaikai
 * @date 2020-8-23 10:35:21
 */
@Controller
@RequestMapping("/mall/distributor/goods")
@Slf4j
public class AdminDistributorGoodsController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private DistributionGoodsApplication distributionGoodsApplication;

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, DistributionGoods params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());
        String hql = "select g from DistributionGoods g where g.status in (1, 2) ";
        Map<String, Object> map = new HashMap<>();

        Goods goods = params.getGoods();
        if (goods != null) {
            if (StringUtils.isNotBlank(goods.getName())) {
                hql += " and g.goods.name like :goodsName";
                map.put("goodsName", "%" + goods.getName() + "%");
            }
        }

        if (params.getDistributorScope() != null) {
            hql += " and g.distributorScope = :scope";
            map.put("scope", params.getDistributorScope());
        }

        if (params.getMinPrice() != null) {
            hql += " and g.goods.defaultPrice >= :minPrice";
            map.put("minPrice", params.getMinPrice());
        }

        if (params.getMaxPrice() != null && (params.getMinPrice() == null || params.getMaxPrice() > params.getMinPrice())) {
            hql += " and g.goods.defaultPrice <= :maxPrice";
            map.put("maxPrice", params.getMaxPrice());
        }

        hql += " order by g.rank desc, g.createTime desc";

        QueryPage<DistributionGoods> page = queryChannelService.findPage(hql, pageRequest.setParams(map), DistributionGoods.class);
        model.addAttribute("page", page);
        model.addAttribute("params", params);

        List<GoodsChannel> channels = queryChannelService.findAll(QGoodsChannel.goodsChannel.level.eq(1).and(QGoodsChannel.goodsChannel.status.eq(1)), GoodsChannel.class);
        model.addAttribute("channels", channels);

        return "mall/distribution/goods/list";
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Model model, long id) {

        DistributionGoods distributionGoods = queryChannelService.findOne(DistributionGoods.class, id);
        List<DistributionGoodsLevel> levels = queryChannelService.findAll(QDistributionGoodsLevel.distributionGoodsLevel.distributionGoods.id.eq(id), DistributionGoodsLevel.class);

        for (DistributionGoodsLevel level : levels) {
            DistributorLevel distributorLevel = queryChannelService.findOne(QDistributorLevel.distributorLevel.level.eq(level.getLevel()), DistributorLevel.class);
            level.setLevelName(distributorLevel.getName());
            level.setFirst((int) ArithUtils.mul(level.getFirstLevelScale(), 100));
            level.setSecond((int) ArithUtils.mul(level.getSecondLevelScale(), 100));
        }

        model.addAttribute("distributionGoods", distributionGoods);
        model.addAttribute("levels", levels);

        return "mall/distribution/goods/detail";

    }

    /**
     * 移除分销池商品
     *
     * @param id 分销池商品id
     */
    @RequestMapping(value = "/remove", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> remove(long id) {
        try {
            DistributionGoods distributionGoods = queryChannelService.findOne(DistributionGoods.class, id);
            Requires.notNull(distributionGoods, "商品不存在");

            distributionGoodsApplication.remove(distributionGoods);
            return ImmutableMap.of("status", true, "message", "移除成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[移除分销池商品异常]", e);
            return ImmutableMap.of("status", false, "message", "移除异常");
        }
    }


    /**
     * 上架分销池商品
     *
     * @param id 分销池商品id
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enable(long id) {
        try {
            DistributionGoods distributionGoods = queryChannelService.findOne(DistributionGoods.class, id);
            Requires.notNull(distributionGoods, "商品不存在");

            distributionGoodsApplication.enable(distributionGoods);
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[上架分销池商品异常]", e);
            return ImmutableMap.of("status", false, "message", "上架异常");
        }
    }


    /**
     * 下架分销池商品
     *
     * @param id 分销池商品id
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disable(long id) {
        try {
            DistributionGoods distributionGoods = queryChannelService.findOne(DistributionGoods.class, id);
            Requires.notNull(distributionGoods, "商品不存在");

            distributionGoodsApplication.disable(distributionGoods);
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[下架分销池商品异常]", e);
            return ImmutableMap.of("status", false, "message", "下架异常");
        }
    }


    /**
     * 批量移除分销池商品
     *
     * @param ids 分销池商品id
     */
    @RequestMapping(value = "/removes", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> remove(String ids) {

        try {

            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            Requires.notEmpty(longIds, "请选择商品");

            List<DistributionGoods> distributionGoodsList = queryChannelService.findAll(QDistributionGoods.distributionGoods.id.in(longIds), DistributionGoods.class);
            distributionGoodsApplication.removes(distributionGoodsList);

            return ImmutableMap.of("status", true, "message", "移除成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[批量移除分销池商品异常]", e);
            return ImmutableMap.of("status", false, "message", "移除异常");
        }
    }

    /**
     * 查看指定分销商
     */
    @RequestMapping(value = "/{id}/queryAssignDistributor", method = RequestMethod.GET)
    public String queryAssignDistributor(Model model, PageParams pageParams, @PathVariable("id") long id) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        String hql = "select d.distributor from DistributionGoodsAssign d where d.distributionGoods.id = :did";
        QueryPage<Distributor> page = queryChannelService.findPage(hql, pageRequest.setParams(ImmutableMap.of("did", id)), Distributor.class);
        model.addAttribute("page", page);
        return "mall/distribution/goods/queryAssignDistributor";
    }

    /**
     * 编辑排序值
     */
    @RequestMapping(value = "/{id}/modifyRank", method = RequestMethod.GET)
    private String modifyRank(Model model, @PathVariable("id") long id) {

        DistributionGoods distributionGoods = queryChannelService.findOne(DistributionGoods.class, id);
        model.addAttribute("distributionGoods", distributionGoods)
                .addAttribute("_method", "PUT");

        return "mall/distribution/goods/modifyRank";
    }

    /**
     * 编辑排序值
     */
    @RequestMapping(value = "/{id}/modifyRank", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> modifyRank(@RequestHeader("X-Requested-With") String requestWith, @ModelAttribute DistributionGoods distributionGoods) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }

            distributionGoodsApplication.modifyRank(distributionGoods);

            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[编辑排序值异常]", e);
            return ImmutableMap.of("status", false);
        }
    }
}
